/**
 */
package forum;

import java.util.ArrayList;

/**
 * @author Olga
 * 
 */
public class Thread {

	private Post root;
	private ArrayList<String> currentViewers;

	/**
	 * 
	 * @param rootPostID
	 *            - unique generated ID of root post
	 * @param subject
	 * @param content
	 * @param author
	 */
	public Thread(int rootPostID, String subject, String content, String author) {
		this.root = new Post(rootPostID, subject, content, null, "", author);
		currentViewers = new ArrayList<String>();
	}

	/**
	 * 
	 * @param rootPost
	 * @param subject
	 * @param content
	 * @param author
	 */
	public Thread(Post rootPost) {
		this.root = rootPost;
		currentViewers = new ArrayList<String>();
	}

	public void addViewer(String viewer) {
		if (!currentViewers.contains(viewer)) {
			this.currentViewers.add(viewer);
		}
	}

	public void removeViewer(String viewer) {
		if (currentViewers.contains(viewer)) {
			this.currentViewers.remove(viewer);
		}
	}

	/**
	 * @return the currentViewers
	 */
	public ArrayList<String> getCurrentViewers() {
		return currentViewers;
	}

	/**
	 * 
	 * @param postID
	 * @return reference to post with postID. If not found, return null.
	 */
	public synchronized Post getPost(int postID) {
		return this.root.findPost(postID);
	}

	/**
	 * @return the ID of root post
	 */
	public synchronized int getID() {
		return this.root.getID();
	}

	/**
	 * @return the root
	 */
	public synchronized Post getRoot() {
		return root;
	}

	/**
	 * @param root
	 *            the root to set
	 */
	public void setRoot(Post root) {
		this.root = root;
	}

	/**
	 * 
	 * @return only root post of the thread. the structure: <br>
	 *         <xmp>ThreadNode PostNode <PostID> <author> <date> <subject>
	 *         <content></xmp>
	 */
	public synchronized String showThreadRoot() {
		String ans = "ThreadNode:\n";
		return ans + this.root.showSinglePost();
	}

	/**
	 * 
	 * @param postID
	 *            - post ID to remove
	 * @return true on success, false else
	 */
	public synchronized boolean removePost(int postID) {
		if (postID == this.root.getID()) {
			return false;
		} else {
			Post toRemove = this.root.findPost(postID);
			Post parent = toRemove.getParent();
			return parent.removeReply(toRemove);
		}
	}

	public String getAuthor() {
		return this.root.getAuthor();
	}

}
